package HtServer;

import HtServer.FileUpload.ImportMeetingFromExcel.ImportMeetingMenber;
import HtServer.Tools.QrCodeUtils;
import HtServer.grpc.MeetingGreeter;
import HtServer.meeting.MeetingItem;
import HtServer.meeting.MeetingItems;
import HtServer.returnObject.ReturnObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import example.servlet.TestServlet;
import io.grpc.servlet.ServletAdapter;
import io.grpc.servlet.ServletServerBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import tools.Configure;
import tools.Tools;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static HtServer.Tools.QrCodeUtils.createImage;

//@WebServlet(name = "HtServlet", value = "/HtServlet")
@WebServlet(urlPatterns = {"/meeting.MeetingGreeter/*"}, asyncSupported = true)
public class HtServlet extends HttpServlet {
//    private final ServletAdapter servletAdapter =
//            new ServletServerBuilder().addService(new MeetingGreeter()).buildServletAdapter();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.setContentType("text/html");
//        response.getWriter().println("<p>HtServlet get method only for test!</p>");


        String action = request.getParameter("action");
        if(action.equals("getqrcode")) {
            response.setContentType("image/png");
            try {
                ServletOutputStream os = response.getOutputStream();
                String url = request.getRequestURL().toString();
                System.out.println(url);
                String requestUrl = Configure.getInstance().getProperties().getProperty("cnooc_meeting_praise");

                System.out.println(requestUrl);

                //requestUrl:需要生成二维码的连接，os：响应输出流
//                QrCodeUtils.encode("dddddd",  os);
                BufferedImage image = createImage(requestUrl);
//                BufferedImage image = ImageIO.read(file);
                ImageIO.write(image, "PNG", response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        //获得小组名字和组号
        else if(action.equals("getgroupname"))
        {
            HashMap<String,String> groupNames = MeetingItems.getInstance().getGroupNames();

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            JSONArray jsonArray = new JSONArray();

            int returntype = ReturnObject.SUCCESS;
            for (String key : groupNames.keySet()) {
                System.out.println("key= "+ key + " and value= " + groupNames.get(key));

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("groupname",groupNames.get(key));
                jsonObject.put("groupid",key);

                String url = Configure.getInstance().getProperties().getProperty("group_qrcode");
                url = url+"?groupid="+key;
                try {
                    BufferedImage image = createImage(url);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(image, "PNG", baos);
                    String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());
                    jsonObject.put("base64","data:image/png;base64,"+base64);
                } catch (Exception e) {
                    System.out.println(e.getStackTrace());
                    returntype = ReturnObject.ERROR;
                }
                jsonArray.add(jsonObject);
            }

            JSONObject groupjson = new JSONObject();
            groupjson.put("groupnames",jsonArray);
            ReturnObject ro = new ReturnObject();
            ro.setJson(groupjson);
            ro.setType(returntype);
            ro.setMsg("成功");

            response.getWriter().println(JSON.toJSON(ro).toString());

        }
        //生成小组二维码地址
        else if(action.equals("getgroupnameQRCode"))
        {
            HashMap<String,String> groupNames = MeetingItems.getInstance().getGroupNames();

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Vector<String> urls = new Vector<>();
            for(String key:groupNames.keySet())
            {
                String url = Configure.getInstance().getProperties().getProperty("group_qrcode");
                url = url+"?groupid="+key;
                try {
                    BufferedImage image = createImage(url);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(image, "PNG", baos);
                    Base64.getEncoder().encodeToString(baos.toByteArray());

                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }






        }
        else if(action.equals("getGroupMembers"))
        {
            String groupid = request.getParameter("groupid");
            System.out.println("groupid:"+groupid);
            Vector<MeetingItem> groupMembers = MeetingItems.getInstance().getGroupMembers(groupid);


            HashMap hm  = new HashMap();
            hm.put("GroupMembers",groupMembers);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            ReturnObject ro = new ReturnObject();

            ro.setJson((JSONObject) (JSON.toJSON(hm)));
            ro.setType(ReturnObject.SUCCESS);
            ro.setMsg("成功");

            response.getWriter().println(JSON.toJSON(ro).toString());
        }


        else if(action.equals("getUserinfo"))
        {
            String userid = request.getParameter("userid");

            MeetingItem mi = MeetingItems.getInstance().getMeetingItem(userid);

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            ReturnObject ro = new ReturnObject();
            ro.setJson((JSONObject) (JSON.toJSON(mi)));
            ro.setType(ReturnObject.SUCCESS);
            ro.setMsg("成功");



            response.getWriter().println(JSON.toJSON(ro).toString());
        }
        //保存用户提交信息
        else if(action.equals("saveMeetingItem"))
        {
            String content = request.getParameter("content");
            String userid = request.getParameter("userid");
            MeetingItem meetingItem = MeetingItems.getInstance().getMeetingItem(userid);
            meetingItem.setContents(content);
            meetingItem.saveMeetingItem2Redis();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            ReturnObject ro = new ReturnObject();
            response.getWriter().printf(ro.ReturnCommonSuccess());
        }
        //增加人员
        else if(action.equals("addMeetuser"))
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            String id = UUID.randomUUID().toString();
            String name = request.getParameter("name");
            String groupid = request.getParameter("groupid");
            String groupname = request.getParameter("groupname");
            String order = request.getParameter("order");

            MeetingItem mi = new MeetingItem();
            mi.setId(id);
            mi.setName(name);
            mi.setGroupname(groupname);
            mi.setGroupid(groupid);
            mi.setOrder(order);
            mi.saveMeetingItem2Redis();
            MeetingItems.getInstance().addItem(mi);

            ReturnObject ro = new ReturnObject();
            response.getWriter().printf(ro.ReturnCommonSuccess());
        }
        //删除人员
        else if(action.equals("delMeetuser"))
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            String id = request.getParameter("id");
            System.out.println("id = "+id);
            MeetingItems.getInstance().delMeetingItem(id);
            ReturnObject ro = new ReturnObject();
            response.getWriter().printf(ro.ReturnCommonSuccess());
        }
        //修改人员
        else if(action.equals("editMeetuser"))
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            String id = request.getParameter("id");
            String name = request.getParameter("name");
            String groupid = request.getParameter("groupid");
            String groupname = request.getParameter("groupname");
            String order = request.getParameter("order");

            MeetingItem mi = MeetingItems.getInstance().getMeetingItem(id);
            if (mi != null) {
                mi.setName(name);
                mi.setGroupid(groupid);
                mi.setGroupname(groupname);
                mi.setOrder(order);
                mi.saveMeetingItem2Redis();
                ReturnObject ro = new ReturnObject();
                response.getWriter().printf(ro.ReturnCommonSuccess());
            }




        }

        else if(action.equals("getLikeResult"))
        {
            String resultnum = request.getParameter("resultnum");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            int num = 20;
            try {
                num = Integer.parseInt(resultnum);
            } catch (Exception e) {

            }

            JSONObject result = MeetingItems.getInstance().getTopLikeJSON(num);
            ReturnObject ro = new ReturnObject();
            ro.setJson(result);
            ro.setType(ReturnObject.SUCCESS);
            ro.setMsg("成功");
            response.getWriter().printf(JSON.toJSON(ro).toString());

        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        if (ServletAdapter.isGrpc(request))
        if(isGrpc(request))
        {
            System.out.println("dogrpc");

//            servletAdapter.doPost(request, response);
        } else {
            System.out.println(" not dogrpc");



            String action = request.getParameter("action");
            System.out.println("action:"+action);

            if(action.equals("dlMeetingExcel")) {


                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss");
                String formattedDate = now.format(formatter);
                System.out.println("当前日期和时间（到秒）: " + formattedDate);
                System.out.println("下载excel");
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                String encodedFilename = URLEncoder.encode("会议记录"+formattedDate, "UTF-8").replaceAll("\\+", "%20");
//                String contentDisposition = "attachment; filename*=UTF-8''" + encodedFilename;

//                response.setHeader("Content-Disposition", "attachment; filename=\"会议记录"+formattedDate+".xlsx\"");
//                response.setHeader("Content-Disposition", "attachment; filename=\"会议记录meeting"+formattedDate+".xlsx\"");
                try {
                    setHeaderWithEncodedFilename(response, "会议记录"+formattedDate+".xlsx");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // 将Excel写入到输出流中
                OutputStream outputStream = response.getOutputStream();
                ImportMeetingMenber importMeetingMenber =new ImportMeetingMenber();
                importMeetingMenber.writeToExcle(outputStream);
                outputStream.flush();
                outputStream.close();
            }
            if(action.equals("dlMeetingExcelTemplate")) {

                String filePath = "/会议人员模版.xlsx";
                String fileName = "会议人员模版.xlsx"; // 客户端保存的文件名
                // 设置响应内容类型和头信息
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

                // 读取文件并写入到响应输出流中
                try (FileInputStream in = new FileInputStream(filePath);
                     OutputStream out = response.getOutputStream()) {

                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = in.read(buffer)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }
            }

            //获得根据领域分组信息
            else if (action.equals("getGroupByField")) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                HashMap hashMap = MeetingItems.getInstance().getMeetingItemByLingyu();
                System.out.println(JSON.toJSONString(hashMap));


                ReturnObject ro = new ReturnObject();
                JSONObject jo = new JSONObject();
                jo.put("groupbyfield",JSON.toJSON(hashMap));
                ro.setJson(jo);
                ro.setType(ReturnObject.SUCCESS);
                ro.setMsg("成功");
                System.out.println(ro.toString());
                response.getWriter().write(JSON.toJSON(ro).toString());
            }
            //全部领域随机
            else if (action.equals("getGroupByAllField")) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                List list  = MeetingItems.getInstance().getMeetingItemByLingyuRandom();
                System.out.println(JSON.toJSONString(list));

                ReturnObject ro = new ReturnObject();
                JSONObject jo =new JSONObject();
                jo.put("radomuser",list);
                ro.setJson(jo);
                ro.setType(ReturnObject.SUCCESS);
                ro.setMsg("成功");

                response.getWriter().println(JSON.toJSON(ro).toString());

            }
            //根据领域返回随机人员
            else if (action.equals("getRandomUserByField")) {
                String lingyu = request.getParameter("lingyu");
                String num = request.getParameter("num");
                System.out.println("lingyu:"+lingyu);
                System.out.println("num:"+num);



//                LinkedList linkedList =  MeetingItems.getInstance().getMeetingItemByLingyu(lingyu);

               List list =MeetingItems.getInstance().getMeetingItemByLingyuRandom(lingyu,Integer.parseInt(num))  ;


                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");

                ReturnObject ro = new ReturnObject();

                JSONObject jo =new JSONObject();
                jo.put("radomuser",list);
                ro.setJson(jo);
                ro.setType(ReturnObject.SUCCESS);
                ro.setMsg("成功");

                response.getWriter().println(JSON.toJSON(ro).toString());
            }


            else
            {
                response.setContentType("text/html");
                response.getWriter().println("<p>Hello non-gRPC2 client!</p>");

            }

        }
    }
    public static void setHeaderWithEncodedFilename(HttpServletResponse response, String filename) throws UnsupportedEncodingException {
        // RFC 5987字符集和语言设置
        String encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        String contentDisposition = "attachment; filename=\"" + encodedFilename+"\"";
        response.setHeader("Content-Disposition", contentDisposition);
    }

    private boolean isGrpc(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.startsWith("application/grpc");
    }
}
